package com.leicx.guli.product.web;

import java.util.Objects;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * @author daxiong
 * @date 2022/7/24 下午3:18
 */
public class TaskTest {

    static ExecutorService executor = new ThreadPoolExecutor(10, 20, 20, TimeUnit.SECONDS,
            new LinkedBlockingDeque<>(50), Executors.defaultThreadFactory(), new ThreadPoolExecutor.AbortPolicy());

    public static void main(String[] args) {
        CompletableFuture<Integer> future = CompletableFuture.supplyAsync(() -> {
            System.out.println("异步线程开始");
            int i = 10 / 0;
            System.out.println("结果计算完成");
            return i;
        }, executor)
                .whenComplete((result, exception) ->
                        System.out.println("异步线程计算结果是：" + result + "，异常是：" + exception))
                .exceptionally((throwable -> {
                    System.out.println("进入异常处理。。。");
                    return 10;
                }))
                .handle((result, exception) -> {
                    System.out.println("进入handle处理...");
                    if (Objects.isNull(exception)) {
                        return result * 2;
                    } else {
                        return 0;
                    }
                });
        Integer result = null;
        try {
            result = future.get();
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println("结果是：" + result);
    }
}
